package threading;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


public class Demo7 {


    public static final int COUNT = 10_000_000;
    public static void main(String[] args) {
        long beg = System.currentTimeMillis();
        int[] arr = new int[COUNT];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int)(Math.random()*100);
        }

        FutureTask<Integer> task1 = new FutureTask<Integer>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int even = 0;
                for (int i = 0; i < arr.length; i+=2) {
                    even += arr[i];
                }

                System.out.println("下标为偶数的和:" + even);
                return even;
            }
        });

        Thread t1 = new Thread(task1);
        t1.start();


        FutureTask<Integer> task2 = new FutureTask<Integer>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int odd = 0;
                for (int i = 1; i < arr.length; i+=2) {
                    odd += arr[i];
                }

                System.out.println("下标为奇数的和:" + odd);
                return odd;
            }
        });
        Thread t2 = new Thread(task2);
        t2.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            int sum = task1.get() + task2.get();
            System.out.println("总和:" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println("执行时间:" + (end - beg) + "ms");


    }


}


